import { useState } from 'react';
import { DropdownToolbar } from 'md-editor-rt';
import styles from './index.less';

import { emojis } from './data';

interface EmojiExtensionProp {
  editorId: string;
  onChange: (v: string) => void;
}

const EmojiExtension = (props: EmojiExtensionProp) => {
  const [state, setState] = useState({
    visible: false,
  });

  const emojiHandler = (emoji: string) => {
    // 获取输入框
    const textarea = document.querySelector(`#${props.editorId}-textarea`) as HTMLTextAreaElement;
    // 获取选中的内容
    const selection = window.getSelection()?.toString();
    // 获取鼠标位置
    const endPoint = textarea.selectionStart;

    // 根据鼠标位置分割旧文本
    // 前半部分
    const prefixStr = textarea.value.substring(0, endPoint);
    // 后半部分
    const suffixStr = textarea.value.substring(endPoint + (selection?.length || 0));

    props.onChange(`${prefixStr}${emoji}${suffixStr}`);

    setTimeout(() => {
      textarea.setSelectionRange(endPoint, endPoint + 1);
      textarea.focus();
    }, 0);
  };

  const onChange = (visible: boolean) => {
    setState({
      visible,
    });
  };

  return (
    <DropdownToolbar
      title="emoji"
      visible={state.visible}
      onChange={onChange}
      trigger={
        <svg
          className="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          width="22"
          height="22"
        >
          <path
            d="M510.944 960c-247.04 0-448-200.96-448-448s200.992-448 448-448 448 200.96 448 448-200.96 448-448 448z m0-832c-211.744 0-384 172.256-384 384s172.256 384 384 384 384-172.256 384-384-172.256-384-384-384z"
            fill=""
          />
          <path d="M512 773.344c-89.184 0-171.904-40.32-226.912-110.624-10.88-13.92-8.448-34.016 5.472-44.896 13.888-10.912 34.016-8.48 44.928 5.472 42.784 54.688 107.136 86.048 176.512 86.048 70.112 0 134.88-31.904 177.664-87.552 10.784-14.016 30.848-16.672 44.864-5.888 14.016 10.784 16.672 30.88 5.888 44.864C685.408 732.32 602.144 773.344 512 773.344zM368 515.2c-26.528 0-48-21.472-48-48v-64c0-26.528 21.472-48 48-48s48 21.472 48 48v64c0 26.496-21.504 48-48 48zM656 515.2c-26.496 0-48-21.472-48-48v-64c0-26.528 21.504-48 48-48s48 21.472 48 48v64c0 26.496-21.504 48-48 48z" />
        </svg>
      }
      overlay={
        <div className={styles.emojiContainer}>
          <ol className={styles.emojis}>
            {emojis.map((emoji, index) => {
              return (
                <li
                  key={`emoji-${index}`}
                  className={styles.emojiItem}
                  onClick={() => {
                    emojiHandler(emoji);
                  }}
                >
                  {emoji}
                </li>
              );
            })}
          </ol>
        </div>
      }
    />
  );
};

export default EmojiExtension;
